package com.yuyu.qingmangmall.product.exception;

import com.yuyu.common.exception.BigCodeEnume;
import com.yuyu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 */
@Slf4j
//@ControllerAdvice(basePackages ="com.yuyu.qingmangmall.product.controller")
//@ResponseBody
@RestControllerAdvice(basePackages ="com.yuyu.qingmangmall.product.controller")
public class QingmangmallExceptionControllerAdvice {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class}) // 捕获的错误类型
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("错误信息{},错误类型{}",e.getMessage(),e.getClass());
        // 获得校验的结果
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
//            item.getDefaultMessage(); 拿到错误信息
//            item.getField();  拿到错误属性名称
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BigCodeEnume.VALID_EXCEPTION.getCode(),BigCodeEnume.VALID_EXCEPTION.getMessage()).put("data",errorMap);
    }

    @ExceptionHandler(value = {Throwable.class})
    public R handleException(Throwable throwable){
        log.error("错误信息{},错误类型{}",throwable.getMessage(),throwable.getClass());

        log.error("错误：{}",throwable);
        return R.error(BigCodeEnume.UNKNOW_EXCEPTION.getCode(),BigCodeEnume.UNKNOW_EXCEPTION.getMessage());
    }
}
